<?php
/**
 * User: ppjun378
 * Data: 2018/10/23
 * Time: 11:30
 */
namespace App\Service;

use App\Model\Assets;
use App\Model\AssetsAttrs;
use App\Model\AssetsAttrValues;
use App\Model\Borrows;
use App\Model\Companys;
use App\Model\Receives;
use App\Model\SendBacks;
use Excel;
use \Exception;

class AssetsService
{
    /**
     * 获取资产列表数据
     * @param $request
     * @return mixed
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function dataList($request)
    {
        $keyword = $request->input('keyword', '');

        $cateid = (int) $request->input('category_id', '');
        $name = $request->input('name', '');
        $coding = $request->input('codding', '');
        $sn = $request->input('sn', '');
        $user_name = $request->input('user_name', '');
        $location = $request->input('location', '');
        $use_the_company_id = (int) $request->input('use_the_company_id', '');
        $department_id = (int) $request->input('department_id', '');
        $status = (int) $request->input('status', '');
        $order_method = (int) $request->input('order_method', 0);

        $size = $request->input('pagenum', 10); // 每页显示的数据条数
        $page = $request->input('page', 1);
        $fields = ['assets.id', 'coding', 'use_the_company_id', 'category_id', 'category.name as category_name', 'assets.name', 'specification', 'sn', 'unit', 'money', 'assets.company_id', 'companys.company_name', 'assets.department_id', 'purchase_date', 'assets.user_name as personnel_id', 'personnels.personnel_name as user_name', 'administrator', 'area', 'location', 'use_period', 'supplier', 'source', 'note', 'image', 'assets.sort', 'assets.status'];

        $data = Assets::select($fields)
            ->join('category', 'category.id', '=', 'assets.category_id')
            ->join('companys', 'companys.id', '=', 'assets.company_id')
            ->leftJoin('personnels', 'personnels.id', '=', 'assets.user_name')
            ->when($cateid, function ($query) use ($cateid) {
                return $query->where('assets.category_id', $cateid); // 资产分类
            })
            ->when($name, function ($query) use ($name) {
                return $query->where('assets.name', 'like', '%' . $name . '%'); // 资产名称
            })
            ->when($coding, function ($query) use ($coding) {
                return $query->where('assets.coding', 'like', '%' . $coding . '%'); // 资产编码
            })
            ->when($sn, function ($query) use ($sn) {
                return $query->where('assets.sn', 'like', '%' . $sn . '%'); // SN码
            })
            ->when($user_name, function ($query) use ($user_name) {
                return $query->where('assets.user_name', 'like', '%' . $user_name . '%'); // 使用人
            })
            ->when($location, function ($query) use ($location) {
                return $query->where('assets.locaction', 'like', '%' . $location . '%'); // 存放地点
            })
            ->when($use_the_company_id, function ($query) use ($use_the_company_id) {
                return $query->where('assets.use_the_company_id', $use_the_company_id); // 使用公司
            })
            ->when($department_id, function ($query) use ($department_id) {
                return $query->where('assets.department_id', $department_id); // 使用部门
            })
            ->when($status, function ($query) use ($status) {
                return $query->where('assets.status', $status); // 资产状态
            })
            ->where(function ($query) use ($keyword) {
                // $query->orWhere('user_name', 'like', '%' . $keyword . '%');
                // ->orWhere('coding', 'like', '%' . $keyword . '%');
                if ($keyword) {
                    // $query->where('assets.name', 'like', '%' . $keyword . '%');
                    // $query->whereRaw('concat(`coding`,`specification`,`sn`,`unit`,`money`,`location`,`note`) like ' . '\'%' . $keyword . '%\'');
                    // $query->whereRaw('concat(`coding`,`specification`,`sn`,`unit`,`location`,`note`) like ' . '\'%' . $keyword . '%\'');
                    $query->orWhere('assets.name', 'like', '%' . $keyword . '%');
                    $query->orWhere('assets.coding', 'like', '%' . $keyword . '%');
                    $query->orWhere('assets.sn', 'like', '%' . $keyword . '%');
                    $query->orWhere('assets.unit', 'like', '%' . $keyword . '%');
                    $query->orWhere('assets.location', 'like', '%' . $keyword . '%');
                    $query->orWhere('assets.note', 'like', '%' . $keyword . '%');
                }
                // $query->orWhere('coding', 'like', '%' . $keyword . '%');

            })
            ->when($order_method, function ($query) use ($order_method) {
                if ($order_method == 1) {
                    return $query->orderBy('assets.coding', 'asc');
                } elseif ($order_method == 2) {
                    return $query->orderBy('assets.coding', 'desc');
                } elseif ($order_method == 3) {
                    return $query->orderBy('assets.purchase_date', 'asc');
                } elseif ($order_method == 4) {
                    return $query->orderBy('assets.purchase_date', 'desc');
                }
            })
            ->orderBy('assets.updated_at', 'desc')

            ->paginate($size);
        // dump(DB::getQueryLog());
        $list['code'] = 0;
        $list['msg'] = "查询成功";
        $list['count'] = count($data);
        $data = $data->toArray();

        $l = array();
        $m = array();
        foreach ($data['data'] as $key => $val) {

            if (!empty($val['department_id'])) {
                // 查询使用公司名称
                $l = Companys::select('company_name as department_name')
                    ->where('id', '=', $val['department_id'])
                    ->first()
                    ->toArray();

            } else {
                $l['department_name'] = null;
            }
            // unset($data['data'][$key]['department_id']);
            $data['data'][$key]['department_name'] = $l['department_name'];

            if (!empty($val['use_the_company_id'])) {
                // 查询使用部门名称
                $m = Companys::select('company_name as use_the_company_name')
                    ->where('id', '=', $val['use_the_company_id'])
                    ->first()
                    ->toArray();
            } else {
                $m['use_the_company_name'] = null;
            }

            // unset($data['data'][$key]['use_the_company_id']);
            $data['data'][$key]['use_the_company_name'] = $m['use_the_company_name'];

            $attr_cate_list = AssetsAttrs::select(['attr_name'])
                ->where('attr_type_id', $val['category_id'])
                ->get()
                ->toArray();

            // echo '<pre>';
            // print_r(array_map('array_shift', $attr_cate_list));
            // print_r(array_values($attr_cate_list));

            // //print_r($attr_cate_list);
            // echo '</pre>';

            // 查询扩展属性
            $attr_list = AssetsAttrValues::select(['attr_id', 'attr_name', 'attr_value'])
                ->join('assets_attrs', 'assets_attrs.id', '=', 'assets_attr_values.attr_id')
                ->where('asset_id', $val['id'])
                ->get()
                ->toArray();

            // echo '<pre>';
            // print_r($attr_list);
            // echo '</pre>';

            // 属性
            $data['data'][$key]['attr_list'] = $attr_list;
            $data['data'][$key]['str_attr_value'] = '';
            if (!empty($attr_list)) {
                foreach ($attr_list as $k => $v) {
                    $data['data'][$key]['str_attr_value'] .= $v['attr_name'] . ':' . $v['attr_value'] . ';';
                }

            }

        }

        // echo '<pre>';
        // print_r($l->toArray());
        // print_r($m->toArray());
        // print_r($data['data']);
        // echo '</pre>';

        $list['data'] = $data['data'];
        return $list;

    }

    /**
     * 获取资产详情
     * @param $id
     * @return mixed
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function getDetail($request)
    {
        $id = $request->input('id', '');
        echo $id;
        $field = ['id', 'coding', 'category_id', 'name', 'specification', 'sn', 'unit', 'money', 'use_the_company_id', 'department_id', 'purchase_date', 'user_name', 'administrator', 'company_id', 'area', 'location', 'use_period', 'supplier', 'source', 'note', 'image', 'sort'];
        $data = Assets::select($field)
            ->where('id', $id)
            ->first();
        print_r($data);
        return $data;
    }

    /**
     * 添加/更新 资产
     * @param $request
     * @return mixed
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function store($request)
    {
        $data = $request->all();
        $id = $request->input('id', '');
        $map = [];
        $fields = ['id', 'coding', 'category_id', 'name', 'specification', 'sn', 'unit', 'money', 'use_the_company_id', 'department_id', 'purchase_date', 'user_name', 'administrator', 'company_id', 'area', 'location', 'use_period', 'supplier', 'source', 'note', 'image', 'sort', 'status'];
        foreach ($data as $k => $v) {
            if ($v === null) {$v = '';}

            // 判断是否填写了cdding
            if ($k == 'coding' && $v == '') {
                $start = date('Y-m-d 00:00:00', time());
                $end = date('Y-m-d 23:59:59', time());
                $field = 'count(id)';
                $sum = Assets::select($field)
                    ->whereBetween('created_at', [$start, $end])
                    ->count();
                $v = (int) (date('md', time()) . 10000) + (int) (empty($sum) ? 0 : $sum + 1);
            }

            if ($k == 'department_id' && !empty($v)) {$map['status'] = 1;}
            if (in_array($k, $fields) && !empty($v)) {
                $map[$k] = $v;
            }
        }

        $data_exist = Assets::where('id', $id)->first();
        if ($id && $data_exist) {
            $result = Assets::where('id', $id)->update($map);
        } else {
            $result = Assets::create($map);
        }
        return $result;
    }

    /**
     * 更改
     * @param $request
     * @return bool
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function save($request)
    {
        $id = $request->input('id', '');
        $field = $request->input('field', '');
        $value = $request->input('value', '');
        if ($field) {
            $map[$field] = $value;
            $request = Assets::where('id', $id)->update($map);
            if ($request) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 删除
     * @param $request
     * @return bool|int
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function destory($request)
    {
        $id = $request->input('id', '');
        $res = Assets::destory($id);
        if ($res > 0) {
            return $res;
        } else {
            return false;
        }
    }

    /**
     * 恢复删除
     * @param $request
     * @return mixed
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function restore($request)
    {
        $id = $request->input('id', '');
        $res = Assets::where('id', $id)->restore();
        return $res;
    }

    /**
     * 上传图片
     *
     */
    public static function upload_image($request)
    {

        try {

            $fileCharater = $request->file('asset_images');

            //检测上传的文件是否合肥，返回为true或false
            if (!$fileCharater->isValid()) {
                throw new Exception('非法文件');
            }

            if (empty($fileCharater)) {
                throw new Exception('请选择一个图片');
            }

            //获取上传文件大小
            $filesize = $fileCharater->getClientSize();
            if ($filesize * 1 / 1024 > 2 * 1024) {
                throw new Exception('图片不能超过2M');
            }

            //获取文件的扩展名
            $ext = $fileCharater->getClientOriginalExtension();

            //获取文件的绝对路径
            $path = $fileCharater->getRealPath();

            $rule = ['jpg', 'png', 'gif', 'jpeg'];
            if (!in_array($ext, $rule)) {
                throw new Exception('图片格式必须为jpg,png,gif,jpeg');
            }

            //定义文件名
            $filename = date('Ymdhis') . '.' . $ext;

            $data['asset_images'] = 'http://eam.inforward.com.cn/storage/' . $filename;

            //存储文件。disk里面的public。总的来说，就是调用disk模块里的public配置
            \Storage::disk('public')->put($filename, file_get_contents($path));

            $list['code'] = 0;
            $list['msg'] = "success";
            $list['data'] = $data;

        } catch (Exception $exception) {
            $msg = $exception->getMessage();
            $list['code'] = 1;
            $list['msg'] = $msg;
        }

        return $list;

    }

    /**
     * 批量导入数据
     */
    public static function import_date()
    {
        $filePath = 'storage/exports/0927.xls';
        $filePath = 'storage/exports/821.xls';
        $filePath = 'storage/exports/1404.xls';
        $filePath = 'storage/exports/gy20181224.xls';
        Excel::load($filePath, function ($reader) use (&$result) {
            $rows = $reader->all()->toArray();

            $data = array();
            foreach ($rows[0] as $k => $v) {
                if ($k > 0) {
                    // foreach ($val as $k => $v) {
                    $data[$k]['category_id'] = $v[2];
                    $data[$k]['name'] = $v[3];
                    $data[$k]['purchase_date'] = empty($v[1]) ? date('Y-m-d', time()) : $v[1];
                    $data[$k]['coding'] = $v[4];
                    $data[$k]['area'] = 1;
                    $data[$k]['location'] = $v[5];
                    $data[$k]['company_id'] = 1;
                    $data[$k]['note'] = $v[6];
                    // }
                }
            }

            $result = Assets::insert($data);
            // echo $result;
            return $result;

        });
        return $result;

    }

    /**
     * 获取资产列表数据
     * @param $request
     * @return mixed
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function userDataList($request)
    {
        $status = (int) $request->input('bill_status', '');
        $bill_type = (int) $request->input('bill_type', '');

        $cateid = (int) $request->input('category_id', '');

        $size = $request->input('pagenum', 5); // 每页显示的数据条数
        $page = $request->input('page', 1);
        $fields = ['assets.id', 'coding', 'use_the_company_id', 'category_id', 'category.name as category_name', 'assets.name', 'specification', 'sn', 'unit', 'money', 'assets.company_id', 'companys.company_name', 'assets.department_id', 'purchase_date', 'assets.user_name as personnel_id', 'personnels.personnel_name as user_name', 'administrator', 'area', 'location', 'use_period', 'supplier', 'source', 'note', 'image', 'assets.sort', 'assets.status'];

        $data = Assets::select($fields)
            ->join('category', 'category.id', '=', 'assets.category_id')
            ->join('companys', 'companys.id', '=', 'assets.company_id')
            ->leftJoin('personnels', 'personnels.id', '=', 'assets.user_name')
            ->when($cateid, function ($query) use ($cateid) {
                return $query->where('assets.category_id', $cateid);
            })
            ->when($status, function ($query) use ($status) {
                return $query->where('assets.status', $status); // 资产状态
            })
            ->orderBy('assets.id', 'desc')

            ->paginate($size);
        // dump(DB::getQueryLog());
        $list['code'] = 0;
        $list['msg'] = "查询成功";
        $list['count'] = count($data);
        $data = $data->toArray();

        $l = array();
        $m = array();
        foreach ($data['data'] as $key => $val) {

            if (!empty($val['department_id'])) {
                // 查询使用公司名称
                $l = Companys::select('company_name as department_name')
                    ->where('id', '=', $val['department_id'])
                    ->first()
                    ->toArray();

            } else {
                $l['department_name'] = null;
            }
            // unset($data['data'][$key]['department_id']);
            $data['data'][$key]['department_name'] = $l['department_name'];

            if (!empty($val['use_the_company_id'])) {
                // 查询使用部门名称
                $m = Companys::select('company_name as use_the_company_name')
                    ->where('id', '=', $val['use_the_company_id'])
                    ->first()
                    ->toArray();
            } else {
                $m['use_the_company_name'] = null;
            }

            // unset($data['data'][$key]['use_the_company_id']);
            $data['data'][$key]['use_the_company_name'] = $m['use_the_company_name'];

        }

        // echo '<pre>';
        // print_r($l->toArray());
        // print_r($m->toArray());
        // print_r($data['data']);
        // echo '</pre>';

        $list['data'] = $data['data'];
        return $list;

    }

    /**
     * 用户申请接口 1.领用 2.退还 3.借用
     * @param $request
     * @return mixed
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function select_use_assets($request)
    {
        $select_assets = $request->input('select_assets', '');
        $bill_type = (int) $request->input('bill_type', '');

        $comment = $request->input('comment', ''); // 备注信息
        $start = date('Y-m-d 00:00:00', time()); // 筛选当天开始时间
        $end = date('Y-m-d 23:59:59', time()); // 筛选当天结束时间
        $field = 'count(id)';

        switch ($bill_type) {
            case 1:
                // 领用
                $sum = Receives::select($field)
                    ->whereBetween('created_at', [$start, $end])
                    ->count();

                $map['borrow_number'] = 'LY' . ((int) (date('Ymd', time()) . 100) + (int) (empty($sum) ? 1 : $sum + 1));

                $map['borrow_user'] = 1;
                $map['borrow_date'] = date('Y-m-d', time());
                $map['use_company_id'] = 1;
                $map['borrow_operator'] = 1;
                $map['comment'] = $comment;
                $map['select_assets'] = $select_assets;
                $map['status'] = 0;

                $result = Receives::create($map);
                return $result;

                break;
            case 2:
                //退库
                $sum = SendBacks::select($field)
                    ->whereBetween('created_at', [$start, $end])
                    ->count();

                $map['borrow_number'] = 'JY' . ((int) (date('Ymd', time()) . 100) + (int) (empty($sum) ? 1 : $sum + 1)); // 退库单号

                $map['actual_revert_date'] = date('Y-m-d', time()); //实际退库日期
                $map['borrow_operator'] = 1; //制单人
                $map['comment'] = $comment; //退库备注
                $map['status'] = 0; //状态
                $map['select_assets'] = $select_assets; //退库资产

                $result = SendBacks::create($map);
                return $result;

                break;
            case 3:
                // 借用
                $expect_revert_date = $request->input('expect_revert_date', '');
                $sum = Borrows::select($field)
                    ->whereBetween('created_at', [$start, $end])
                    ->count();

                $map['borrow_number'] = 'JY' . ((int) (date('Ymd', time()) . 100) + (int) (empty($sum) ? 1 : $sum + 1));

                $map['borrow_user'] = 1; //借用人
                $map['borrow_date'] = date('Y-m-d', time()); // 借用日期
                $map['expect_revert_date'] = $expect_revert_date; // 预计归还日期
                $map['borrow_operator'] = 1; // 制单人
                $map['comment'] = $comment;
                $map['select_assets'] = $select_assets;
                $map['status'] = 0; // 借用单状态

                $result = Borrows::create($map);
                return $result;

                break;
        };

    }

}
